package dao.impl;

import bean.dto.Login;
import bean.dto.UserRoomList;
import bean.pojo.Room;
import bean.pojo.User;
import bean.vo.UserVo;
import commons.dbHelper.DBHelper;
import commons.jdbc.basic.JDBCUtil;
import dao.UserDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * dao.impl
 * User: mcw
 * Date: 2024/12/16 上午10:09
 * motto:   春天（spring）没有虫子（bug)
 * Description:
 * Version: V1.0
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User login(Login login) {
        String sql = "select * from user where user_name = ? and password = ?";
        String username = login.getUsername();
        String password = login.getPassword();
        JDBCUtil jdbcUtil = new JDBCUtil();
        User user = new User();
        List<Map<String, Object>> query = jdbcUtil.query(sql, username, password);
        if (query.size() > 0) {
             user.setUserId((Integer) query.get(0).get("user_id"));
             user.setUserName((String) query.get(0).get("user_name"));
             user.setUserSex((String) query.get(0).get("user_sex"));
             user.setUserPhone((String) query.get(0).get("user_phone"));
             user.setFacePhoto((String) query.get(0).get("face_photo"));
             user.setUserAge((Integer) query.get(0).get("user_age"));
        }
        return user;
    }

    @Override
    public UserVo getInfoRole(Integer userId) {
        String sql = "select  u.*,ur.role_id   from   user u ,user_roles ur where u.user_id=ur.user_id and ur.user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> mapList = jdbcUtil.query(sql, userId);
        //转换为user
        if (mapList.size() > 0) {
            UserVo userVo = new UserVo();
            userVo.setUserId((Integer) mapList.get(0).get("user_id"));
            userVo.setUserName((String) mapList.get(0).get("user_name"));
            userVo.setRoleId((Integer) mapList.get(0).get("role_id"));
            return userVo;
        }
        return null;
    }

    @Override
    public Long findByTotal(Integer userId, String userName, String userSex,Integer userAge, String idCardNumber,String userPhone, Integer isOwner, Integer roomId) {
        StringBuffer sql = new StringBuffer("select user_id from user where 1=1");
        List<Object>  parameters=new ArrayList<>();
        if (userId != null) {
            sql.append(" and user_id=? ");
            parameters.add(userId);
        }
        if (userName != null) {
            sql.append(" and user_name like concat ('%',?,'%') ");
            parameters.add(userName);
        }
        if (userSex != null) {
            sql.append(" and user_sex like concat ('%',?,'%') ");
            parameters.add(userSex);
        }
        if (userAge != null) {
            sql.append(" and user_age = ? ");
            parameters.add(userAge);
        }
        if (idCardNumber != null) {
            sql.append(" and id_card_number like concat ('%',?,'%') ");
            parameters.add(idCardNumber);
        }
        if (isOwner != null) {
            sql.append(" and is_owner=? ");
            parameters.add(isOwner);
        }
        if (roomId != 0) {
            sql.append(" and room_id=? ");
            parameters.add(roomId);
        }
        System.out.println("sql:" + sql);
        System.out.println("参数:"+parameters);
        DBHelper dbHelper = new DBHelper();
        List<User> query = dbHelper.getBeanList(User.class,sql.toString(),parameters.toArray());
        if (query!=null) {
            return (long) query.size();
        }
        return 0L;
    }

    @Override
    public List<UserRoomList> userFindBy(Integer page, Integer limit, Integer userId, String userName, String userSex, Integer userAge,String idCardNumber ,String userPhone, Integer isOwner , Integer roomId) {
        StringBuffer sql = new StringBuffer("select u.user_id,u.user_name,u.user_sex,u.user_age,u.id_card_number,u.user_phone,u.is_owner,u.face_photo,u.room_id,u.password,r.room_number from user u  join room r on u.room_id=r.room_id where 1=1");
        List<Object>  parameters=new ArrayList<>();
        if (userId != null) {
            sql.append(" and u.user_id=? ");
            parameters.add(userId);
        }
        if (userName != null) {
            sql.append(" and u.user_name like concat ('%',?,'%') ");
            parameters.add(userName);
        }
        if (userSex != null) {
            sql.append(" and u.user_sex like concat ('%',?,'%') ");
            parameters.add(userSex);
        }
        if (userAge != null) {
            sql.append(" and u.user_age = ? ");
            parameters.add(userAge);
        }
        if (idCardNumber != null) {
            sql.append(" and u.id_card_number like concat ('%',?,'%') ");
            parameters.add(idCardNumber);
        }
        if (userPhone != null) {
            sql.append(" and u.user_phone like concat ('%',?,'%') ");
            parameters.add(userPhone);
        }
        if (isOwner != null) {
            sql.append(" and u.is_owner=? ");
            parameters.add(isOwner);
        }
        if (roomId != 0) {
            sql.append(" and u.room_id=? ");
            parameters.add(roomId);
        }

        sql.append(" order by u.user_id asc ");
        sql.append(" limit " + (page - 1) * limit + "," + limit);
        System.out.println("sql:" + sql);
        System.out.println("参数:"+parameters);
        DBHelper dbHelper = new DBHelper();
        return dbHelper.getBeanList(UserRoomList.class,sql.toString(),parameters.toArray());
    }

    @Override
    public Integer add(User user) {
        String sql ="insert user  (user_name,user_sex,user_age,id_card_number,user_phone,is_owner," +
                "face_photo,room_id,password) values (?,?,?,?,?,?,?,?,?)";
        DBHelper dbHelper = new DBHelper();
        return dbHelper.update(sql,user.getUserName(), user.getUserSex(), user.getUserAge(),user.getIdCardNumber(),
                user.getUserPhone(), user.getIsOwner(), user.getFacePhoto(), user.getRoomId(),user.getPassword());
    }

    @Override
    public Integer deleteById(Integer userId) {
        String sql="delete from user where user_id=? ";
        DBHelper dbHelper = new DBHelper();
        return dbHelper.update(sql,userId);
    }

    @Override
    public Integer update(User user) {
        String sql ="update user set user_name=?,user_sex=?,user_age=?,id_card_number=?,user_phone=?,is_owner=?," +
                "face_photo=?,room_id=?,password=? where user_id = ?";
        DBHelper dbHelper = new DBHelper();
        return dbHelper.update(sql,user.getUserName(), user.getUserSex(),user.getUserAge(), user.getIdCardNumber(), user.getUserPhone(),
                user.getIsOwner(), user.getFacePhoto(), user.getRoomId(),user.getPassword(),user.getUserId());
    }

    /**
     * 查询用户是否存在
     * @param userName
     * @return
     */
    @Override
    public Boolean tfExistUserName(String userName) {
        String sql ="select user_id from user where user_name=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql, userName);
        if (query.size()>0) {
            return false;
        }
        return true;
    }

    /**
     * 用户注册，并绑定角色为普通用户
     * @param user
     * @return
     */
    @Override
    public Integer registerUser(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        String userSex = user.getUserSex();
        Integer userAge = user.getUserAge();
        String userPhone = user.getUserPhone();
        String idCardNumber = user.getIdCardNumber();
        String sql="insert into user(user_name,user_sex,user_age,id_card_number,password,user_phone) values (?,?,?,?,?,?)";
        JDBCUtil jdbcUtil=new JDBCUtil();
        if (userName!=null&&password!=null){
            int update = jdbcUtil.update(sql, userName, userSex, userAge, idCardNumber, password,userPhone);
            //为用户绑定角色
            if (update>0) {
                //拿到刚插入的用户id
                String sql1 = "select user_id from user where user_name=? and password=?";
                List<Map<String, Object>> query = jdbcUtil.query(sql1, userName, password);
                Integer userId = (Integer) query.get(0).get("user_id");
                //查询普通用户的id
                String sql2="select role_id from roles where role_name=?";
                List<Map<String, Object>> list = jdbcUtil.query(sql2,"普通用户");
                Integer roleId = (Integer) list.get(0).get("role_id");
                //绑定角色
                String sql3="insert into user_roles(user_id,role_id) values (?,?)";
                int update1 = jdbcUtil.update(sql3, userId, roleId);
                if (update1>0) {
                    return userId;
                }

            }
        }
        return 0;
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public User findUserById(Integer userId) {
        String sql="select * from user where user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql, userId);
        if (query.size()>0) {
            Map<String, Object> map = query.get(0);
            User user = new User();
            user.setUserId((Integer) map.get("user_id"));
            user.setUserName(map.get("user_name").toString());
            user.setUserSex((String) map.get("user_sex"));
            user.setUserAge((Integer) map.get("user_age"));
            user.setIdCardNumber((String) map.get("id_card_number"));
            user.setUserPhone((String) map.get("user_phone"));
            user.setFacePhoto((String)map.get("face_photo"));
            user.setPassword(map.get("password").toString());
            System.out.println("user:"+user);
            return user;
        }
        return null;
    }

    /**
     * 修改用户基本信息
     * @param user
     * @param userId
     * @return
     */
    @Override
    public Integer updatePersonalInfo(User user, Integer userId) {
        String userName = user.getUserName();
        String password = user.getPassword();
        String userSex = user.getUserSex();
        Integer userAge = user.getUserAge();
        String userPhone = user.getUserPhone();
        String sql="update user set user_name=?,password=?,user_sex=?,user_age=?,user_phone=? where user_id=?";

        JDBCUtil jdbcUtil = new JDBCUtil();
        int update = jdbcUtil.update(sql, userName, password, userSex, userAge,userPhone, userId);
        return update;
    }

    /**
     * 查询除了登录用户外是否还有相同的用户名
     * @param userName
     * @param userId
     * @return
     */
    @Override
    public Boolean tfExistName(String userName, Integer userId) {
        String sql="select * from user where user_name=? and user_id!=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql, userName, userId);
        if (query.size()>0) {
            return false;
        }
        return true;
    }

    /**
     * 更新用户头像路径
     *
     * @param userId 用户角色ID
     * @param relativePath 头像文件的相对路径
     * @return 如果更新成功，返回受影响的行数；如果更新失败，返回0
     */
    @Override
    public Integer updateAvatar(Integer userId, String relativePath) {
        String sql = "update user set face_photo = ? where user_id = ?";
        DBHelper dbHelper = new DBHelper();
        return dbHelper.update(sql, relativePath, userId);
    }

    @Override
    public User findFacePhoto(Integer userId) {
        String sql ="select * from user where user_id =?";
        return new DBHelper().getBean(User.class,sql,userId);
    }

}
